﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Text;
using System.Linq;
using T.FAS.Runtime.Expression.Entity;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Expression.SPI;
using Newtonsoft.Json;
using T.ServiceComponent.DataAccessEx.Core;

namespace T.FAS.Runtime.Expression.Plugin
{
    public class DatabaseHelperExecutor : DynamicObject, IDynamicActionAdapter
    {
        /// <summary>
        /// JS脚本动态调用Dynamic必备函数
        /// 脚本写法：WF.DQ_GetUser();
        /// </summary>
        /// <param name="name">动态调用DynamicObject中的函数名称</param>
        /// <param name="args">参数信息，参数类型必须增加 params</param>
        /// <returns></returns>
        public object DynamicInvoke(string name, params object[] args)
        {
            return ExcuteDatabaseHelper(name, args);
        }

        private object ExcuteDatabaseHelper(string actionID, object[] paramList)
        {
            if (actionID == "GetDatabase")
            {
                return DatabaseHelper.GetDatabase(paramList[0].ToString());
            }
            else if (actionID == "GetDatabaseByConnectionKey")
            {
                return DatabaseHelper.GetDatabaseByConnectionKey(paramList[0].ToString());
            }
            else if (actionID == "GetDbType")
            {
                return DatabaseHelper.GetDbType(paramList[0].ToString());
            }
            else
            {
                throw new FasException(ExprExceptionCode.NotSupported, "Unsupported DatabaseHelper." + actionID);
            }
        }

        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            result = DynamicInvoke(binder.Name, args);
            return true;
        }
    }
}
